"use client";

import { useState, useEffect } from "react";
import { CarSearchParams } from "@/services/api";
import { Drawer, Checkbox, Radio, Slider, Select, Button, Space } from "antd";
import Image from "next/image";
// 品牌数据将在组件中动态导入

interface CarSearchProps {
  onSearch: (params: CarSearchParams) => void;
  initialParams?: CarSearchParams;
}

interface BrandItem {
  brand: string;
  name: string;
  alphabet: string;
  country: string;
  hot: string;
  desc: string;
  story: string;
}

interface BrandGroup {
  letter: string;
  brands: BrandItem[];
}

export default function CarSearch({
  onSearch,
  initialParams = {},
}: CarSearchProps) {
  const [searchParams, setSearchParams] = useState<CarSearchParams>(initialParams);
  const [showFilters, setShowFilters] = useState(false);
  const [carType, setCarType] = useState<"new" | "used" | "all">("all");
  const [open, setOpen] = useState(false);
  const [selectedBrands, setSelectedBrands] = useState<string[]>([]);
  const [selectedPriceRange, setSelectedPriceRange] = useState<[number, number]>([0, 10000000]);
  const [selectedYearRange, setSelectedYearRange] = useState<[number, number]>([2000, 2025]);
  const [selectedMileageRange, setSelectedMileageRange] = useState<[number, number]>([0, 500000]);
  const [brandData, setBrandData] = useState<BrandItem[]>([]);
  const [brandGroups, setBrandGroups] = useState<BrandGroup[]>([]);
  const [selectedCarLevel, setSelectedCarLevel] = useState<string[]>([]);

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  const priceRanges = [
    { label: "不限价格", value: [0, 10000000] },
    { label: "10万以下", value: [0, 100000] },
    { label: "10-30万", value: [100000, 300000] },
    { label: "30-50万", value: [300000, 500000] },
    { label: "50-100万", value: [500000, 1000000] },
    { label: "100万以上", value: [1000000, 10000000] },
  ];

  const yearRanges = [
    { label: "不限年份", value: [2000, 2025] },
    { label: "2023-2025", value: [2023, 2025] },
    { label: "2020-2022", value: [2020, 2022] },
    { label: "2017-2019", value: [2017, 2019] },
    { label: "2017以前", value: [2000, 2016] },
  ];

  const mileageRanges = [
    { label: "不限里程", value: [0, 500000] },
    { label: "1万公里内", value: [0, 10000] },
    { label: "1-3万公里", value: [10000, 30000] },
    { label: "3-5万公里", value: [30000, 50000] },
    { label: "5-10万公里", value: [50000, 100000] },
    { label: "10万公里以上", value: [100000, 500000] },
  ];

  const handleSearch = () => {
    onSearch(searchParams);
  };

  const handleReset = () => {
    const resetParams: CarSearchParams = {};
    setSearchParams(resetParams);
    setCarType("all");
    setSelectedBrands([]);
    setSelectedPriceRange([0, 10000000]);
    setSelectedYearRange([2000, 2025]);
    setSelectedMileageRange([0, 500000]);
    setSelectedCarLevel([]);
    onSearch(resetParams);
  };

  const handleBrandChange = (brands: string[]) => {
    setSelectedBrands(brands);
    const newParams = { ...searchParams };
    if (brands.length === 0) {
      delete newParams.brand;
    } else {
      newParams.brand = brands.join(',');
    }
    setSearchParams(newParams);
  };

  const handlePriceRangeChange = (value: number | number[]) => {
    if (Array.isArray(value) && value.length === 2) {
      const range = value as [number, number];
      setSelectedPriceRange(range);
      const newParams = { ...searchParams };
      newParams.priceRange = range;
      setSearchParams(newParams);
    }
  };

  const handleYearRangeChange = (value: number | number[]) => {
    if (Array.isArray(value) && value.length === 2) {
      const range = value as [number, number];
      setSelectedYearRange(range);
      const newParams = { ...searchParams };
      newParams.yearRange = range;
      setSearchParams(newParams);
    }
  };

  const handleMileageRangeChange = (value: number | number[]) => {
    if (Array.isArray(value) && value.length === 2) {
      const range = value as [number, number];
      setSelectedMileageRange(range);
      const newParams = { ...searchParams };
      newParams.mileageRange = range;
      setSearchParams(newParams);
    }
  };

  // 加载品牌数据
  useEffect(() => {
    const loadBrandData = async () => {
      try {
        const response = await fetch('/branddata.js');
        const text = await response.text();
        
        // 从导出的JS文件中提取数据
        const dataMatch = text.match(/export default (\[[\s\S]*\])/);
        if (dataMatch && dataMatch[1]) {
          const brandData = JSON.parse(dataMatch[1]);
          setBrandData(brandData);
          
          // 按字母分组品牌数据
          const groupedBrands = brandData.reduce((groups: BrandGroup[], brand: BrandItem) => {
            const letter = brand.alphabet.toUpperCase();
            let group = groups.find(g => g.letter === letter);
            if (!group) {
              group = { letter, brands: [] };
              groups.push(group);
            }
            group.brands.push(brand);
            return groups;
          }, [] as BrandGroup[]);
          
          // 按字母排序
          groupedBrands.sort((a: BrandGroup, b: BrandGroup) => a.letter.localeCompare(b.letter));
          setBrandGroups(groupedBrands);
        } else {
          throw new Error('品牌数据格式错误');
        }
      } catch (error) {
        console.error('加载品牌数据失败:', error);
        // 如果加载失败，使用默认数据
        const defaultBrands: BrandItem[] = [
          { brand: "byd", name: "比亚迪", alphabet: "B", country: "中国", hot: "1", desc: "", story: "" },
          { brand: "tesla", name: "特斯拉", alphabet: "T", country: "美国", hot: "0", desc: "", story: "" },
          { brand: "geely", name: "吉利", alphabet: "J", country: "中国", hot: "1", desc: "", story: "" },
          { brand: "toyota", name: "丰田", alphabet: "F", country: "日本", hot: "1", desc: "", story: "" },
          { brand: "honda", name: "本田", alphabet: "B", country: "日本", hot: "1", desc: "", story: "" },
          { brand: "volkswagen", name: "大众", alphabet: "D", country: "德国", hot: "1", desc: "", story: "" },
        ];
        setBrandData(defaultBrands);
      }
    };
    
    loadBrandData();
  }, []);

  const handleApplyFilters = () => {
    onSearch(searchParams);
    setOpen(false);
  };

  const handleCarTypeChange = (type: "new" | "used" | "all") => {
    setCarType(type);
    const newParams = { ...searchParams };
    if (type === "all") {
      delete newParams.type;
    } else {
      newParams.type = type;
    }
    setSearchParams(newParams);
  };

  const handleCarLevelChange = (levels: string[]) => {
    setSelectedCarLevel(levels);
    const newParams = { ...searchParams };
    if (levels.length === 0) {
      delete newParams.carLevel;
    } else {
      newParams.carLevel = levels.join(',');
    }
    setSearchParams(newParams);
  };

  return (
    <div className="w-full max-w-6xl mx-auto">
      {/* 搜索框 */}
      <div className="relative mb-6">
        <div className="relative">
          <div className="absolute left-4 top-1/2 transform -translate-y-1/2 cursor-pointer" onClick={showDrawer}>
            <Image src="/filter.svg" alt="Search" width={20} height={20} />
          </div>
          <input
            type="text"
            placeholder="搜索品牌、车型或关键词..."
            className="w-full px-12 py-4 text-lg border border-gray-300 rounded-full shadow-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-[#F9F9F9] text-black"
            value={searchParams.keyword || ""}
            onChange={(e) =>
              setSearchParams({ ...searchParams, keyword: e.target.value })
            }
            onKeyPress={(e) => e.key === "Enter" && handleSearch()}
          />
          <button
            onClick={handleSearch}
            className="absolute right-2 top-1/2 transform -translate-y-1/2 bg-blue-600 hover:bg-blue-700 text-white px-8 py-2 rounded-full font-semibold transition-colors"
          >
            搜索
          </button>
        </div>
      </div>
      <Drawer 
        title="筛选条件" 
        placement="left" 
        onClose={onClose} 
        open={open}
        width={400}
        extra={
          <Space>
            <Button onClick={handleReset}>重置</Button>
            <Button type="primary" onClick={handleApplyFilters}>应用</Button>
          </Space>
        }
      >
        {/* 车辆类型 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">车辆类型</h3>
          <Radio.Group 
            value={carType} 
            onChange={(e) => handleCarTypeChange(e.target.value)}
            className="w-full"
          >
            <Space  className="w-full">
              <Radio value="all">全部</Radio>
              <Radio value="new">新车</Radio>
              <Radio value="used">二手车</Radio>
            </Space>
          </Radio.Group>
        </div>

        {/* 车辆级别 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">车辆级别</h3>
          <Checkbox.Group 
            value={selectedCarLevel} 
            onChange={handleCarLevelChange}
            className="w-full"
          >
            <Space direction="horizontal" wrap className="w-full">
              <Checkbox value="sedan">轿车</Checkbox>
              <Checkbox value="suv">SUV</Checkbox>
              <Checkbox value="mpv">MPV</Checkbox>
            </Space>
          </Checkbox.Group>
        </div>

        {/* 品牌选择 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">品牌</h3>
          <div className="max-h-60 overflow-y-auto">
            <Checkbox.Group 
              value={selectedBrands} 
              onChange={handleBrandChange}
              className="w-full"
            >
              <Space direction="vertical" className="w-full">
                {brandGroups.length > 0 ? (
                  brandGroups.map((group) => (
                    <div key={group.letter}>
                      <div className="bg-gray-100 px-3 py-1 font-semibold text-gray-600 sticky top-0 z-10">
                        {group.letter}
                      </div>
                      {group.brands.map((brand: BrandItem) => (
                        // <div key={brand.brand} className="flex items-center py-1">
                          <Checkbox key={brand.brand} value={brand.brand} className="flex !items-center h-8">
                          <div className="flex items-center space-x-2">
                            <Image 
                              src={`/car-logo/${brand.brand}.png`} 
                              alt={brand.name}
                              width={24}
                              height={24}
                            />
                            <span>{brand.name}</span>
                            {brand.hot === "1" && (
                              <span className="bg-red-500 text-white text-xs px-1 rounded">热</span>
                            )}
                          </div>
                        </Checkbox>
                        // </div>
                      ))}
                    </div>
                  ))
                ) : (
                  brandData && brandData.map((brand: BrandItem) => (
                    <Checkbox key={brand.brand} value={brand.brand}>
                      <div className="flex items-center space-x-2">
                        <Image 
                          src={`/car-logo/${brand.brand}.png`} 
                          alt={brand.name}
                          width={24}
                          height={24}
                          className="rounded"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement;
                            target.src = '/car-logo/default.png';
                          }}
                        />
                        <span>{brand.name}</span>
                        {brand.hot === "1" && (
                          <span className="bg-red-500 text-white text-xs px-1 rounded">热</span>
                        )}
                      </div>
                    </Checkbox>
                  ))
                )}
              </Space>
            </Checkbox.Group>
          </div>
        </div>

        {/* 价格区间 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">价格区间</h3>
          <div className="px-2">
            <Slider
              range
              min={0}
              max={1000000}
              step={10000}
              value={selectedPriceRange}
              onChange={handlePriceRangeChange}
              tooltip={{  formatter: (value) => `${(value / 10000).toFixed(1)}万`
        }}
            />
            <div className="flex justify-between text-sm text-gray-600 mt-2">
              <span>{(selectedPriceRange[0] / 10000).toFixed(1)}万</span>
              <span>{(selectedPriceRange[1] / 10000).toFixed(1)}万</span>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-2 mt-3">
            {priceRanges.map((range) => (
              <Button
                key={range.label}
                size="small"
                type={selectedPriceRange[0] === range.value[0] && selectedPriceRange[1] === range.value[1] ? "primary" : "default"}
                onClick={() => handlePriceRangeChange(range.value as [number, number])}
              >
                {range.label}
              </Button>
            ))}
          </div>
        </div>

        {/* 生产年份 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">生产年份</h3>
          <div className="px-2">
            <Slider
              range
              min={2000}
              max={2025}
              step={1}
              value={selectedYearRange}
              onChange={handleYearRangeChange}
            />
            <div className="flex justify-between text-sm text-gray-600 mt-2">
              <span>{selectedYearRange[0]}年</span>
              <span>{selectedYearRange[1]}年</span>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-2 mt-3">
            {yearRanges.map((range) => (
              <Button
                key={range.label}
                size="small"
                type={selectedYearRange[0] === range.value[0] && selectedYearRange[1] === range.value[1] ? "primary" : "default"}
                onClick={() => handleYearRangeChange(range.value as [number, number])}
              >
                {range.label}
              </Button>
            ))}
          </div>
        </div>

        {/* 行驶里程 */}
        <div className="mb-6">
          <h3 className="text-lg font-semibold mb-3">行驶里程</h3>
          <div className="px-2">
            <Slider
              range
              min={0}
              max={200000}
              step={1000}
              value={selectedMileageRange}
              onChange={handleMileageRangeChange}
                 tooltip={{  formatter: (value) => `${(value / 10000).toFixed(1)}万公里`
        }}
            
            />
            <div className="flex justify-between text-sm text-gray-600 mt-2">
              <span>{(selectedMileageRange[0] / 10000).toFixed(1)}万公里</span>
              <span>{(selectedMileageRange[1] / 10000).toFixed(1)}万公里</span>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-2 mt-3">
            {mileageRanges.map((range) => (
              <Button
                key={range.label}
                size="small"
                type={selectedMileageRange[0] === range.value[0] && selectedMileageRange[1] === range.value[1] ? "primary" : "default"}
                onClick={() => handleMileageRangeChange(range.value as [number, number])}
              >
                {range.label}
              </Button>
            ))}
          </div>
        </div>
      </Drawer>
    </div>
  );
}
